package icu.mohan.erp.call.service;

import java.util.Map;
import java.util.UUID;

import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.client.RestTemplate;

import com.alibaba.fastjson2.JSON;

import icu.mohan.erp.call.config.CallProperties;
import icu.mohan.erp.call.model.CommonResponse;
import icu.mohan.erp.call.util.SignatureUtil;
import lombok.AllArgsConstructor;

/**
 * 外呼标准API请求
 * 
 * @author yanglihao
 */
@AllArgsConstructor
public class CallApiService {

    private CallProperties callProperties;

    private RestTemplate restTemplate;

    public CommonResponse post(String url, Map<String, String> requestBody) throws Exception {

        long timestamp = System.currentTimeMillis();

        // 计算签名
        String signature = SignatureUtil.generateSignature(callProperties.getAppSecret(), timestamp, requestBody);

        // 获取请求头
        String nonce = UUID.randomUUID().toString().replaceAll("-", "");
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        headers.add("appkey", callProperties.getAppKey());
        headers.add("timestamp", String.valueOf(timestamp));
        headers.add("sign", signature);
        headers.add("nonce", nonce);

        // 封装请求
        HttpEntity<String> request = new HttpEntity<String>(JSON.toJSONString(requestBody), headers);

        // 发送请求
        String finalUrl = callProperties.getBaseUrl() + url;
        ResponseEntity<CommonResponse> response = restTemplate.postForEntity(finalUrl, request, CommonResponse.class);

        return response.getBody();
    }
}
